import { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from "react";
import documentService from "@/api/services/mes/sopService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import { Button, Input, InputNumber, Modal } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import { toast } from "sonner";
import type { SopDocument } from "./entity";
import { Upload } from "@/components/upload";
import type { UploadFile, UploadProps } from "antd/es/upload/interface";

interface SopDocumentProps {
	parentId?: React.Key;
	status?: string;
	isView?: boolean;
}

export interface SopDocumentHandles {
	getAddList: () => SopDocument[];
	getUpdateList: () => SopDocument[];
	getDeleteIds: () => React.Key[];
}

const SopDocumentPage = forwardRef<SopDocumentHandles, SopDocumentProps>(({ parentId, status, isView }, ref) => {
	const [loading, setLoading] = useState(false);
	const [list, setList] = useState<SopDocument[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [editedRowKey, setEditedRowKey] = useState<React.Key>();
	// 添加一个状态来跟踪临时ID
	const [tempIds, setTempIds] = useState<React.Key[]>([]);
	const [addList, setAddList] = useState<SopDocument[]>([]);
	const [updateList, setUpdateList] = useState<SopDocument[]>([]);
	const [deleteIds, setDeleteIds] = useState<React.Key[]>([]);

	// 上传相关状态
	const [uploadModalVisible, setUploadModalVisible] = useState(false);
	const [fileList, setFileList] = useState<UploadFile[]>([]);
	const [uploading, setUploading] = useState(false);

	useImperativeHandle(
		ref,
		() => ({
			getAddList: () => addList,
			getUpdateList: () => updateList,
			getDeleteIds: () => deleteIds,
		}),
		[addList, updateList, deleteIds],
	);

	useEffect(() => {
		const newAddList = list.filter((item) => item.id && tempIds.includes(item.id));
		setAddList(newAddList);
		const updateList = list.filter((item) => item.id && !tempIds.includes(item.id));
		setUpdateList(updateList);
	}, [list]);

	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 403;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	//表格列定义
	const columns: ColumnsType<SopDocument> = [
		{
			title: "文件名称",
			width: 120,
			key: "fileName",
			dataIndex: "fileName",
		},
		{
			title: "文件类型",
			width: 120,
			key: "fileType",
			dataIndex: "fileType",
		},
		{
			title: "文件大小",
			width: 120,
			key: "fileSize",
			dataIndex: "fileSize",
		},
		{
			title: "开始页码",
			width: 120,
			key: "startIndex",
			dataIndex: "startIndex",
			render: (text, record) => (
				<InputNumber
					value={text}
					onChange={(value) => handleFieldChange(record.id, "startIndex", value)}
					style={{ width: "100%" }}
				/>
			),
		},
		{
			title: "结束页码",
			width: 120,
			key: "endIndex",
			dataIndex: "endIndex",
			render: (text, record) => (
				<InputNumber
					value={text}
					onChange={(value) => handleFieldChange(record.id, "endIndex", value)}
					style={{ width: "100%" }}
				/>
			),
		},
		{
			title: "备注",
			width: 120,
			key: "remark",
			dataIndex: "remark",
			render: (text, record) => (
				<Input value={text} onChange={(e) => handleFieldChange(record.id, "remark", e.target.value)} />
			),
		},
	];

	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => (col.key ? String(col.key) : "")),
	);

	// 处理字段变更
	const handleFieldChange = (id: string, field: string, value: any) => {
		let inputValue: any = null;
		// 如果是checkbox的值，将布尔值转换为数字值（true为1，false为0）
		if (typeof value === "boolean") {
			inputValue = value ? 1 : 0;
		} else if (value instanceof Date) {
			// 处理日期格式
			inputValue = dayjs(value).format("YYYY-MM-DD");
		} else {
			inputValue = value;
		}

		setList((prevData) => prevData.map((item) => (item.id === id ? { ...item, [field]: inputValue } : item)));
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	const filteredColumns = useMemo(() => {
		return [...columns.filter((col) => selectedValues.includes(String(col.key)) || col.key === "operation")].sort(
			(a, b) => {
				const originalIndex = columns.findIndex((c) => c.key === a.key);
				const targetIndex = columns.findIndex((c) => c.key === b.key);
				return originalIndex - targetIndex;
			},
		);
	}, [selectedValues]);

	//加载表格数据
	const fetchList = () => {
		if (!parentId) return;

		setLoading(true);
		documentService
			.getdocuments(parentId)
			.then((res) => {
				setList(res);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		if (parentId) {
			fetchList();
		} else {
			// 初始化时清空状态
			setList([]);
			setSelectedRowKeys([]);
			setTempIds([]);
			setAddList([]);
			setUpdateList([]);
			setDeleteIds([]);
		}
	}, [parentId]);

	//检验是否输入值
	const validatePartsBeforeAdd = (): boolean => {
		return true;
	};

	// 在删除方法中修改判断逻辑
	const handleDelete = () => {
		// 如果没有选中行，直接返回
		if (selectedRowKeys.length === 0) {
			return;
		}

		// 根据 selectedRowKeys 获取 list 中的元素，并提取 attachmentId
		const selectedAttachmentIds = list
			.filter((item) => selectedRowKeys.includes(item.id))
			.map((item) => item.attachmentId);
		if (selectedAttachmentIds.length > 0) {
			for (const selectedAttachmentId of selectedAttachmentIds) {
				documentService
					.deleteFile(selectedAttachmentId)
					.then(() => {
						toast.success("文件删除成功");
					})
					.catch((error) => {
						toast.error(`文件删除失败: ${error.message || "未知错误"}`);
					});
			}
		}

		// 更新删除ID列表
		const newDeleteIds = [...deleteIds];

		// 将已有ID但不在deleteIds中的ID添加到deleteIds
		for (const key of selectedRowKeys) {
			const item = list.find((item) => item.id === key);
			if (item?.id && !tempIds.includes(item.id)) {
				// 如果不在临时ID列表中，则添加到删除列表
				if (!newDeleteIds.includes(item.id)) {
					newDeleteIds.push(item.id);
				}
			}
		}

		// 更新deleteIds状态
		setDeleteIds(newDeleteIds);

		// 从列表中移除选中的行
		setList((prevList) => prevList.filter((item) => !selectedRowKeys.includes(item.id)));
		// 从tempIds中移除被删除的临时ID
		setTempIds((prevTempIds) => prevTempIds.filter((id) => !selectedRowKeys.includes(id)));
		// 清空选中状态
		setSelectedRowKeys([]);
	};

	// 处理上传按钮点击
	const handleUpload = () => {
		validatePartsBeforeAdd();

		setUploadModalVisible(true);
	};

	// 处理上传模态窗关闭
	const handleUploadModalCancel = () => {
		setUploadModalVisible(false);
		setFileList([]);
	};

	// 处理文件上传
	const handleFileUpload = async () => {
		if (fileList.length === 0) {
			toast.warning("请选择要上传的文件");
			return;
		}

		setUploading(true);

		console.log("上传文件", fileList);
		// 上传每个文件
		for (const file of fileList) {
			if (file.originFileObj) {
				// 使用修改后的uploadFile方法
				await documentService
					.uploadFile(file.originFileObj)
					.then((res) => {
						toast.success("文件上传成功");
						setUploadModalVisible(false);
						const attachment = res;

						const newId = Date.now().toString();
						const newDetail: SopDocument = {
							id: newId,
							manageId: parentId,
							fileName: attachment.fileName,
							fileType: attachment.fileType,
							fileSize: attachment.fileSize,
							attachmentId: attachment.id,
						};

						// 添加到临时ID列表
						setTempIds((prev) => [...prev, newId]);
						setList((prev) => [...prev, newDetail]);
					})
					.catch((error) => {
						toast.error(`上传失败: ${error.message || "未知错误"}`);
					})
					.finally(() => {
						setUploading(false);
					});
			}
		}
	};

	// 处理文件列表变化
	const handleFileListChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
		setFileList(newFileList);
	};

	// 上传前检查
	const beforeUpload = (file: File) => {
		// 这里可以添加文件类型、大小等检查
		const isLt10M = file.size / 1024 / 1024 < 10;
		if (!isLt10M) {
			toast.error("文件必须小于10MB!");
			return false;
		}
		return true;
	};

	return (
		<>
			<div className="flex justify-between mb-4">
				<div className="flex gap-2">
					<Button type="primary" disabled={status === "published" || isView} onClick={handleUpload}>
						上传
					</Button>
					<Button danger disabled={selectedRowKeys.length === 0 || status === "published" || isView} onClick={handleDelete}>
						删除
					</Button>
				</div>
				<TableToolbar
					onRefresh={() => fetchList()}
					onSizeChange={setTableSize}
					columns={columns}
					selectedValues={selectedValues}
					onColumnChange={setSelectedValues}
				/>
			</div>
			<Table
				rowKey="id"
				size={tableSize}
				scroll={{ x: "max-content", y: tableScrollY }}
				loading={loading}
				pagination={false}
				columns={filteredColumns}
				dataSource={list}
				rowSelection={{
					type: "checkbox",
					selectedRowKeys: selectedRowKeys,
					onChange: (selectedKeys) => {
						setSelectedRowKeys(selectedKeys as React.Key[]);
					},
				}}
			/>
			{/* 上传文件模态窗 */}
			<Modal
				title="上传文件"
				open={uploadModalVisible}
				onCancel={handleUploadModalCancel}
				footer={[
					<Button key="cancel" onClick={handleUploadModalCancel}>
						取消
					</Button>,
					<Button key="upload" type="primary" loading={uploading} onClick={handleFileUpload}>
						上传
					</Button>,
				]}
			>
				<Upload
					beforeUpload={beforeUpload}
					onChange={handleFileListChange}
					fileList={fileList}
					multiple={false}
					thumbnail={false}
					maxCount={1}
				/>
				<div className="mt-4 text-gray-500">单个文件大小不超过10MB</div>
			</Modal>
		</>
	);
});

export default SopDocumentPage;
